package com.sskj.motherboard.server;

import com.sskj.motherboard.handler.CustomProtocolDecoder;
import com.sskj.motherboard.handler.CustomProtocolEncoder;
import com.sskj.motherboard.handler.FrameMessageHandler;
import com.sskj.motherboard.handler.strategy.FrameMessageHandlerFactory;
import com.sskj.motherboard.properties.NettyProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class NettyServer {

    @Autowired
    private NettyProperties nettyProperties;

    @Autowired
    private FrameMessageHandlerFactory frameMessageHandlerFactory;

    public void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new CustomProtocolEncoder());
                            socketChannel.pipeline().addLast(new CustomProtocolDecoder());
                            socketChannel.pipeline().addLast(new FrameMessageHandler(frameMessageHandlerFactory));
                        }
                    })
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = serverBootstrap.bind(nettyProperties.getPort()).sync();
            log.info("Netty Server started on port {}", nettyProperties.getPort());

            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
